import markdown
from django.core.paginator import Paginator
from django.http import Http404, HttpResponseNotAllowed
from django.shortcuts import render
from django.views import View
from django.views.decorators.http import require_http_methods, require_GET

from notebook.models import Notebook, Category


@require_http_methods(["GET", "POST"])  # 表示可以用 GET 方法和 POST 方法
def notebook_list_view(request):
    notebooks = Notebook.objects.all()
    paginator = Paginator(notebooks, 4)
    page_obj = paginator.get_page(1)
    return render(request, "notebook_list.html", {"notebooks": page_obj})


@require_GET  # 表示只能用 GET 方法
def notebook_list_page_view(request, page):
    notebooks = Notebook.objects.all()
    paginator = Paginator(notebooks, 4)
    page_obj = paginator.get_page(page)
    return render(request, "notebook_list.html", {"notebooks": page_obj})


# 基于函数的视图
def notebook_content_view(request, id):
    try:
        notebook = Notebook.objects.get(id=id)
        return render(request, "notebook_content.html",
                      {"notebook": notebook, "content": markdown.markdown(notebook.content)})
    except Notebook.DoesNotExist:
        return Http404("笔记不存在")


# 基于类的视图
class NotebookCategoryView(View):
    def get(self, request):
        try:
            categories = Category.objects.all()
            return render(request, "notebook_categories.html", {"categories": categories})
        except Category.DoesNotExist:
            return Http404("分类不存在")

    def post(self, request):
        return HttpResponseNotAllowed(["GET"])
